/* 
 * Enterprise Library Extensions - DI + ORM.
 * Copyright (C) 2006
 *
 * GNU General Public License
 *
 * This program is free software; you can redistribute 
 * it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 */
using System;
using System.Collections;
using ELE.Common.Util;
using ELE.EnterpriseLibrary.Naming.Configuration;
using ELE.EnterpriseLibrary.Common.Logging;

namespace ELE.EnterpriseLibrary.Naming
{
  /// <summary>
  /// Summary description for RemoteContextManager.
  /// 
  /// Author : Miguel Curi
  /// 
  /// </summary>
  public class RemoteContextManager : LoggingObjectBase
  {
    /// <summary>
    /// TCP protocol key inherited from InitialContext.REMOTING_PROTOCOL_TCP
    /// </summary>
    public const string REMOTING_PROTOCOL_TCP = InitialContext.REMOTING_PROTOCOL_TCP;
    /// <summary>
    /// HTTP protocol key inherited from InitialContext.REMOTING_PROTOCOL_HTTP
    /// </summary>
    public const string REMOTING_PROTOCOL_HTTP = InitialContext.REMOTING_PROTOCOL_HTTP;

    private string mPort;
    private string mHost;
    private string mProtocol;
    private string mConfigurationRootDir;
    private InitialContext mCtx;
    /// <summary>
    /// Default constructor
    /// </summary>
    public RemoteContextManager()
    {
    }
    /// <summary>
    /// The port in the remote server
    /// </summary>
    public string Port
    {
      get { return mPort; }
      set { mPort = value; }
    }
    /// <summary>
    /// The host name or ip address
    /// </summary>
    public string Host
    {
      get { return mHost; }
      set { mHost = value; }
    }
    /// <summary>
    /// Context to which this manager is attached 
    /// </summary>
    public InitialContext Context
    {
      get { return mCtx; }
      set { mCtx = value; }
    }
    /// <summary>
    /// The root directory of the remoting configuration files
    /// </summary>
    public string ConfigRootDir
    {
      get { return mConfigurationRootDir; }
      set { mConfigurationRootDir = value; }
    }
    /// <summary>
    /// The communication protocol. either <see cref="REMOTING_PROTOCOL_TCP"/> or <see cref="REMOTING_PROTOCOL_HTTP"/>.
    /// The default is <see cref="REMOTING_PROTOCOL_TCP"/>
    /// </summary>
    public string Protocol
    {
      get
      {
        if(mProtocol == null)
        {
          return REMOTING_PROTOCOL_TCP;
        }
        return mProtocol;
      }
      set
      {
        if(value != null)
        {
          if(StringUtils.EqualsIgnoreCase(value, REMOTING_PROTOCOL_TCP) || 
            StringUtils.EqualsIgnoreCase(value, REMOTING_PROTOCOL_HTTP))
          {
            mProtocol = value;
          }

        }
      }
    }
    /// <summary>
    /// Gets a remote link name of the form <see cref="Protocol"/>://<see cref="Host"/>:<see cref="Port"/>
    /// </summary>
    public string RemoteLinkName
    {
      get
      {
        if(this.Port != null && this.Host != null)
        {
          System.Text.StringBuilder linkName = new System.Text.StringBuilder();
          linkName.Append(this.Protocol).Append(CompositeNameParser.SECTION_DELIMITER);
          linkName.Append(CompositeNameParser.NAME_DELIMITER).Append(CompositeNameParser.NAME_DELIMITER);
          linkName.Append(this.Host).Append(CompositeNameParser.SECTION_DELIMITER);
          linkName.Append(this.Port);
          return linkName.ToString();
        }
        return null;
      }
    }

    /// <summary>
    /// Get a handle of a remote object
    /// </summary>
    /// <param name="pName"></param>
    /// <returns></returns>
    public object GetRemoteObject(string pName)
    {
      if(pName == null)
      {
        this.LogError("RemoteContextManager can't find an object if the given name is null (GetObject(null) is not a valid call");
        return null;
      }
      if(this.Host == null)
      {
        this.LogError("RemoteContextManager configured incorrectly, a Host name is needed in order to locate the remote context");
        return null;
      }
      if(this.Port == null)
      {
        this.LogError("RemoteContextManager configured incorrectly, a Port number is needed in order to locate the remote context");
        return null;
      }
      string rlink = this.RemoteLinkName;
      if(rlink != null)
      {
        if(!pName.StartsWith(CompositeNameParser.NAME_DELIMITER))
        {
          rlink += CompositeNameParser.NAME_DELIMITER;
        }
        rlink += pName;
      }
      try
      {
        this.LogDebug("RemoteContextManager attempting to locate remote resource " + rlink);

        string compLocation = this.ConfigRootDir;
        if(!pName.StartsWith(CompositeNameParser.NAME_DELIMITER))
        {
          if(compLocation.EndsWith(CompositeNameParser.NAME_DELIMITER))
          {
            compLocation += pName;
          }
          else
          {
            compLocation += CompositeNameParser.NAME_DELIMITER + pName;
          }
        } 
        else
        {
          if(compLocation.EndsWith(CompositeNameParser.NAME_DELIMITER))
          {
            compLocation += pName.Substring(1);
          }
          else
          {
            compLocation += pName;
          }
        }
        compLocation += NamingContextConstants.CONFIG_EXTENSION;

        ComponentConfiguration conf = this.Context.ParseComponentConfiguration(compLocation);
        if(conf != null)
        {
          try
          {
            System.Reflection.Assembly a = System.Reflection.Assembly.Load(conf.ComponentType.AssemblyName);
            
            return Activator.GetObject(a.GetType(conf.ComponentType.ClassName), rlink);
          }
          catch(Exception re)
          {
            this.LogError("RemoteContextManager failed to locate resource named " + 
                            rlink + " in context, due to reflection or activation problems",
                            re);
            throw re;

          }
        }
        else
        {
          this.LogError("RemoteContextManager could not locate resource named " + pName + " in context, No Configuration File Found",null);
          throw new ComponentConfigurationException("RemoteContextManager could not locate resource named " + pName + " in context with root at " + this.ConfigRootDir);
        }

      }
      catch(Exception e)
      {
        this.LogError("RemoteContextManager failed to locate object " + rlink + " due to : ", e);
        throw e;
      }
    }

  }
}
